#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
using namespace std;

namespace myclient
{
    class udpClient
    {
    public:
        udpClient(const string &serverip, const uint16_t &serverport)
            : _serverip(serverip), _serverport(serverport), _socketfd(-1)
        {
        }
        void initClient()
        {
            // 客户端只需要打开套接字即可，绑定的事情交给os去做，因为每次绑定的端口号都是不一样的
            _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_socketfd == -1)
            {
                cerr << "socket fail :" << errno << strerror(errno) << endl;
                exit(1);
            }
            cout << "socket success :" << _socketfd << endl;
            // 其余的无需去做
        }
        static void *read_message(void *args)
        {
            int fd = *static_cast<int *>(args);
            pthread_detach(pthread_self());
            while (true)
            {
                char buffer[1024];
                struct sockaddr_in server;
                socklen_t len = sizeof(server);
                // 接受信息
                ssize_t s = recvfrom(fd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&server, &len);
                if (s >= 0)
                {
                    buffer[s] = 0;
                }
                cout << buffer << endl;
            }
            return nullptr;
        }
        void run()
        {
            // 一个线程发送信息，另一个线程接受信息
            pthread_create(&_reader, nullptr, read_message, (void *)&_socketfd);
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            server.sin_port = htons(_serverport);
            server.sin_family = AF_INET;
            string message;
            char line[1024];
            for (;;)
            {
                // cout << "请输入" << endl;
                // cin >> line;
                fprintf(stderr, "Enter# ");
                fflush(stderr);
                fgets(line, sizeof(line), stdin);
                line[strlen(line) - 1] = 0; // 去掉换行
                message = line;
                //cout<<message<<endl;
                sendto(_socketfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
            }
        }
        ~udpClient()
        {
        }

    private:
        string _serverip;
        uint16_t _serverport;
        int _socketfd;
        pthread_t _reader; // 创建线程来读信息
    };
}